package com.hai.udp;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.FilterEvent;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * fileDesc
 * Created by huanghp on 2020/3/26.
 * Email h1132760021@sina.com
 */
public class MinaClient {
    static NioDatagramConnector connector;
    static IoSession session;

    public static void main(String[] args) {
        connector = new NioDatagramConnector();
        connector.setHandler(new MyHandler("MinaClient"));
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("utf-8"))));
        connector.getFilterChain().addLast("beanc", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
        ConnectFuture connFuture = connector.connect(new InetSocketAddress("localhost", 60030));
        connFuture.addListener(new IoFutureListener<IoFuture>() {
            @Override
            public void operationComplete(IoFuture future) {
                ConnectFuture connFuture = (ConnectFuture) future;
                if (connFuture.isConnected()) {
                    session = future.getSession();
                    try {
                        sendData();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("client connection failed");
                }
            }
        });
    }

    private static void sendData() throws InterruptedException {
        for (int i = 0; i < 1; i++) {
            long free = Runtime.getRuntime().freeMemory();
            IoBuffer buffer = IoBuffer.allocate(8);
            buffer.putLong(free);
            buffer.flip();
            String msg = "a msg for send";
            session.write(msg);
           /* try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                throw new InterruptedException(e.getMessage());
            }*/
        }

        session.write(new Cat("花花", 23));
        session.write(new User("xiaoming", "pwdMIng"));
    }

}
